const {connection,mysqlDao} = require('../utils/jdbc-connection')
const BaseDao = require("./base-dao");

/**
 * 博客操作
 */
class BlogDao extends BaseDao{
    constructor() {
        super();
    }

    /**
     * 分页查询文章索引
     * @param pageIndex：页码
     * @param pageSize：每页显示条数
     * @param options:条件
     * @return arr[{id,title,content}]
     */
    getArticlesList(pageIndex = 1,pageSize = 20,options = {}){
        const {userId,categoryId} = options
        const start = pageIndex - 1
        let sql = 'select a.*,b.category_name from article a,category b where a.category_id = b.id order by create_time desc limit ?,? '
        return connection(sql,[start*pageSize,pageIndex*pageSize])
    }

    /**
     * 获取一篇文章详情
     * @param id
     * @returns {{}}
     */
    getArticleById(id) {
        let sql = 'select * from article where id = ?'
        return connection(sql,[id])
    }

    /**
     * 插入一条文章，并返回主键
     * @param article
     * @returns {{}}
     */
    insertOneArticle(article,) {
        const {title,content,description,createTime,userId,categoryId} = article
        let sql = 'insert into article(title,content,description,create_time,user_id,category_id) values(?,?,?,?,?,?);'
        return connection(sql,[title,content,description,createTime,userId,categoryId])
    }

    /**
     * 更新文章内容
     * @param article
     * @returns {{}}
     */
    updateOneArticle(article){
        const {id,title,content,description,updateTime,categoryId} = article
        let sql = 'update article set title = ?,content = ?,description = ?,update_time = ?,category_id = ? where id = ?'
        return connection(sql,[title,content,description,updateTime,categoryId,id])
    }
    /**
     * 删除文章
     * @param id
     * @returns {{}}
     */
    deleteArticleById(id) {
        let sql = 'delete from article where id = ?'
        const promise = connection(sql,[id])
        let obj = {}
        promise.then(res => {
            obj = res
        })
        return obj
    }

    /**
     * 通过分类名称获取分类id
     * @param categoryName
     * @returns {{}}
     */
    getCategoryIdByName(categoryName){
        let sql = 'select id from category where category_name = ?'
        return connection(sql,[categoryName])
    }

    /**
     * 查询所有文章类型
     * @returns {Promise<unknown>}
     */
    queryCategoryList(){
        let sql = 'select * from category'
        return connection(sql,[])
    }

    /**
     * ajax回调，
     * @param responseText
     * @returns {*} ajax返回值
     */
    insertResult(error,responseText,field){
        console.log("responseText:",responseText)
        return responseText
    }


}

module.exports = BlogDao;
